home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
src
/
fig20_15.jar
/
Ch20
/
Fig20_15
/
fig20_15.cpp
Wrap
C/C++ Source or Header
|
1997-11-11
|
2KB
|
51 lines
// Fig. 20.15: fig20_15.cpp
// Testing Standard Library vector class template
// element-manipulation functions
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
const int SIZE = 6;
int a[ SIZE ] = { 1, 2, 3, 4, 5, 6 };
vector< int > v( a, a + SIZE );
ostream_iterator< int > output( cout, " " );
cout << "Vector v contains: ";
copy( v.begin(), v.end(), output );
cout << "\nFirst element of v: " << v.front()
<< "\nLast element of v: " << v.back();
v[ 0 ] = 7; // set first element to 7
v.at( 2 ) = 10; // set element at position 2 to 10
v.insert( v.begin() + 1, 22 ); // insert 22 as 2nd element
cout << "\nContents of vector v after changes: ";
copy( v.begin(), v.end(), output );
try {
v.at( 100 ) = 777; // access element out of range
}
catch ( out_of_range e ) {
cout << "\nException: " << e.what();
}
v.erase( v.begin() );
cout << "\nContents of vector v after erase: ";
copy( v.begin(), v.end(), output );
v.erase( v.begin(), v.end() );
cout << "\nAfter erase, vector v "
<< ( v.empty() ? "is" : "is not" ) << " empty";
v.insert( v.begin(), a, a + SIZE );
cout << "\nContents of vector v before clear: ";
copy( v.begin(), v.end(), output );
v.clear(); // clear calls erase to empty a collection
cout << "\nAfter clear, vector v "
<< ( v.empty() ? "is" : "is not" ) << " empty";
cout << endl;
return 0;
}